package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func AuthMiddleWare() gin.HandlerFunc{
	return func(c *gin.Context) {
		// 获取客户端cookie并校验
		cookie, err := c.Cookie("abc")
		if err == nil{
			if cookie == "123"{
				c.Next()
				return
			}
		}
		// 返回错误
		c.JSON(http.StatusUnauthorized,gin.H{"error": "err"})
		// 若验证不通过，不再调用后续的操作
		c.Abort()
		return
	}
}

func main(){
	r := gin.Default()
	r.GET("/login", func(c *gin.Context) {
		// 设置cookie
		c.SetCookie("abc", "123", 600, "/",
			"127.0.0.1", false, true)
		// 返回信息
		c.String(200, "login success!")
	})
	r.GET("/home", AuthMiddleWare(),func(c *gin.Context) {
		c.JSON(200, gin.H{"data":"home"})
	})

	r.Run(":8006")
}
